package com.zlyx.easy.log.aspect;

import java.util.ArrayList;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.exception.BusinessException;
import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.utils.HttpUtils.HttpResponse;
import com.zlyx.easy.core.utils.RequestUtils;
import com.zlyx.easy.log.annotations.EasyLog;
import com.zlyx.easy.log.aspect.abstracts.AbstractLogAspect;

@Aspect
@SpringBean(todo = { "请求切面" })
public class WebAspect extends AbstractLogAspect {

	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) ||"
			+ "@annotation(org.springframework.web.bind.annotation.PostMapping) ||"
			+ "@annotation(org.springframework.web.bind.annotation.GetMapping)")
	public void web() {
	}

	@Around("web()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		try {
			super.init(pjp);
			// 如果EasyLog注解存在，那么优先执行EasyLog注解切面
			if (realMethod.isAnnotationPresent(EasyLog.class)) {
				return pjp.proceed();
			}
			// 类层是否开启
			EasyLog easyClassLog = realClass.getAnnotation(EasyLog.class);
			if (easyClassLog == null || Boolean.FALSE == easyClassLog.isLog()) {
				return pjp.proceed();
			}
			String url = RequestUtils.getRequest().getRequestURI();
			return doAround(pjp, url, realMethod.getName());
		} catch (BusinessException e) {
			Logger.err(pjp.getTarget().getClass(), e);
			return isReturnException() ? HttpResponse.failure(e.getCode(), e) : null;
		} catch (Throwable t) {
			Logger.err(pjp.getTarget().getClass(), t);
			return isReturnException() ? HttpResponse.failure(t) : null;
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (excludeUrls == null) {
			excludeUrls = new ArrayList<>();
		}
		excludeUrls.add("/error");
		excludeUrls.add("/swagger-resources");
	}
}
